package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.service.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class SystemLogUtil {

    @Autowired
    ISystemLogService systemLogService;

    public  void writeLog(JoinPoint joinPoint){
        //错误二，记录日志的保存操作也是会记录日志的，就会一直死循环
        //如果是记录日志的service操作，就不进入日志
        if(joinPoint.getTarget() instanceof ISystemLogService){
            return;
        }
        SystemLog log = new SystemLog();
        log.setOpTime(new Date());
        log.setOpUser(UserContext.getCurrentUser());
        //在aop中的配置，跟mvc没有关系，不能直接注入请求
        log.setOpIp(UserContext.getRequest().getRemoteAddr());
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        log.setFunction(className+":"+methodName);
        try {
            log.setParams(new ObjectMapper().writeValueAsString(joinPoint.getArgs()));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //systemLogService.insert(log);
    }
}
